const router = require("koa-router")();
const NoticeModel = require("../models/notice.js");
const ResultHelper = require("../utils/resultHelper.js");
const VerifyHelper = require("../utils/verifyHelper.js");



router.get("/notices", async ctx => {
	let {
		page,
		limit,
		title
	} = ctx.query;
	if (page == undefined) {
		page = 0
	}
	if (limit == undefined) {
		limit = 10
	}
	const query = {};
	
	// 构建查询条件
	if (title) {
		query.title = {
			$regex: ctx.query.title
		};
	}
	

	var data = await NoticeModel.find(query).skip(Number(page - 1) * limit).limit(Number(limit));
	var total = await NoticeModel.find(query).countDocuments();
	ctx.body = {
		code: 200,
		data: data,
		total,
		msg: "ok"
	}

})

router.post("/notice", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id,
		title,
		content,
		create,
		modify
	} = ctx.request.body;
	
	if (!title) {
		return ResultHelper.errInfo422(ctx, "请填写公告名称")
	}
	
	if (!content) {
		return ResultHelper.errInfo422(ctx, "请填写公告内容")
	}
	
	if (!id) {
		
		const noticePost = new NoticeModel({
			id,
			title,
			content,
			create,
			modify
		});
		const res = await noticePost.save();
		ctx.body = {
			code: 200,
			msg: "添加成功"
		}
	} else {
		// 已存在数据
		// 获取下数据的内容
		const item = await NoticeModel.findOne({
			id: ctx.request.body.id
		});
		const res = await NoticeModel.updateOne({
			id: id
		}, {
			$set: {
				id,
				title: ctx.request.body.title ? ctx.request.body.title : item.title,
				content: ctx.request.body.content ? ctx.request.body.content : item.content,
				create: ctx.request.body.create ? ctx.request.body.create : item.create,
				modify: formatDateHelper.date()
			}
		});
		ctx.body = {
			code: 200,
			msg: "编辑成功"
		}
		
	}
})

router.get("/del/notice", async ctx => {
	VerifyHelper.token(ctx)
	const {
		id
	} = ctx.request.query;
	let res = await NoticeModel.deleteOne({
		id: id
	});
	ctx.body = {
		code: 200,
		msg: '删除成功'
	}
})


module.exports = router;
